<template>
  <div class="user-header">
    <el-button type="primary" @click="addUser">+ 新增</el-button>
    <el-form :inline="true" :model="formInline">
      <!-- 人员查询 -->
      <el-form-item label="人员查询">
        <el-input v-model="formInline.keyword" placeholder="请输入人员名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="table">
    <el-table :data="tableData" style="width: 100%">
      <el-table-column
          v-for="item in tableLabel"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
          :width="item.width ? item.width : 125"
      />

      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <el-pagination
        background
        class="pager"
        layout="prev, pager, next"
        :total="config.total"
        :current-page.sync="config.page"
        :page-size="config.limit"
        @current-change="handleChange"
    />
    <el-dialog
        v-model="dialogVisible"
        :title="action === 'add' ? '新增用户' : '编辑用户'"
        width="35%"
        :before-close="handleClose"
    >
      <el-form :model="formUser" :rules="rules" ref="userForm">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="formUser.name" placeholder="请输入姓名"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input v-model.number="formUser.age" placeholder="请输入年龄"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item class="select-clear" label="性别" prop="sex">
              <el-select v-model="formUser.sex" placeholder="请选择">
                <el-option label="男" value="1"/>
                <el-option label="女" value="0"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birth">
              <el-date-picker
                  v-model="formUser.birth"
                  type="date"
                  placeholder="请输入"
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="地址" prop="addr">
            <el-input v-model="formUser.addr" placeholder="请输入地址"/>
          </el-form-item>
        </el-row>
        <el-row style="justify-content: flex-end">
          <el-form-item>
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="onSubmit">确定</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, onMounted, nextTick } from "vue";
import { ElMessage,ElMessageBox } from 'element-plus';
const { proxy } = getCurrentInstance();

const tableLabel = reactive([
  { prop: "name", label: "姓名" },
  { prop: "age", label: "年龄" },
  { prop: "sexLabel", label: "性别" },
  { prop: "birth", label: "出生日期", width: 200 },
  { prop: "addr", label: "地址", width: 400 },
]);

const tableData = ref([]); // 使用 ref([]) 确保是响应式的

const getUserList = async () => {
  const data = await proxy.$api.getUserList(config);
  if (data && data.list && Array.isArray(data.list)) {
    tableData.value = data.list.map(item => ({
      ...item,
      sexLabel: item.sex === 0 ? "女" : "男",
    }));
    config.total = data.count || 0;
  } else {
    console.warn("Unexpected API response", data);
    ElMessage({ message: "获取数据失败", type: "error" });
  }
};
const action = ref("add");
const formUser = reactive({});
const dialogVisible = ref(false);

const formInline = reactive({ keyword: '' });
const config = reactive({
  name: '' ,
  total: 0,
  page: 1,
  limit: 10 // 每页显示的数据数量
});

const rules = reactive({
  name: [{ required: true, message: "姓名是必填项", trigger: "blur" }],
  age: [
    { required: true, message: "年龄是必填项", trigger: "blur" },
    { type: "number", message: "年龄必须是数字" },
  ],
  sex: [{ required: true, message: "性别是必选项", trigger: "change" }],
  birth: [{ required: true, message: "出生日期是必选项" }],
  addr: [{ required: true, message: "地址是必填项" }],
});

const addUser = () => {
  action.value = "add";
  dialogVisible.value = true;
};

const handleEdit = (val) => {
  action.value = "edit";
  dialogVisible.value = true;
  nextTick(() => {
    Object.assign(formUser, { ...val, sex: "" + val.sex });
  });
};

const handleDelete =  (val) => {
  ElMessageBox.confirm("确定删除该用户吗？").then(async ()=>{
    await proxy.$api.deleteUser({id:val.id});
    ElMessage({
      shapeFlag:true,
      message: "删除成功",
      type: "success"
    })
     await getUserList();
  })
};

const handleSearch =  () => {
  config.name = formInline.keyword;
  config.page = 1; // 每次搜索从第一页开始
  getUserList();
};



const handleClose = () => {
  proxy.$refs["userForm"].resetFields();
  dialogVisible.value = false;
};

const handleCancel = () => {
  proxy.$refs["userForm"].resetFields();
  dialogVisible.value = false;
};

const timeFormat = (time) => {
  if (isNaN(new Date(time).getTime())) {
    throw new Error('Invalid date');
  }

  const date = new Date(time);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const dateStr = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${dateStr}`;
};

const handleChange = (page) => {

  config.page = page
  getUserList()
};

const onSubmit = () => {
  proxy.$refs["userForm"].validate(async (valid) => {
    if (valid) {
      let res = null;
      formUser.birth = /^\d{4}-\d{2}-\d{2}$/.test(formUser.birth) ? formUser.birth : timeFormat(formUser.birth);
      if (action.value === "add") {
        res = await proxy.$api.addUser(formUser);
      } else if (action.value === "edit") {
        res = await proxy.$api.editUser(formUser);
      }
      if (res) {
        dialogVisible.value = false;
        proxy.$refs["userForm"].resetFields();
        await getUserList();
        ElMessage({ message: "操作成功", type: "success" });
      }
    } else {
      ElMessage({
        showClose: true,
        message: "请输入正确的内容",
        type: "error",
      });
    }
  });
};

onMounted(async () => {
  await getUserList();
});
</script>

<style scoped lang="less">
.user-header{
  display:flex;
  justify-content:space-between;
}
.table{
  position:relative;
  height:520px;
  .pager{
    position:absolute;
    right:10px;
    bottom:9px;
  }
  .el-table{
    width:100%;
    height:500px;
  }
}
.select-clearn{
  display:flex;
}
</style>